package com.hottv.meeting.videomeeting;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.herewhite.sdk.Room;
import com.herewhite.sdk.WhiteBroadView;
import com.herewhite.sdk.domain.EventEntry;
import com.herewhite.sdk.domain.EventListener;
import com.herewhite.sdk.domain.Promise;
import com.herewhite.sdk.domain.SDKError;
import com.herewhite.sdk.domain.Scene;
import com.hottv.meeting.videomeeting.common.MeetingConfig;
import com.hottv.meeting.videomeeting.common.MeetingUtils;
import com.hottv.meeting.videomeeting.module.agora.AgoraManager;
import com.hottv.meeting.videomeeting.module.agora.AgoraUtils;
import com.hottv.meeting.videomeeting.module.agora.data.MsgItem;
import com.hottv.meeting.videomeeting.module.agora.view.MemAdapter;
import com.hottv.meeting.videomeeting.module.agora.view.MsgAdapter;
import com.hottv.meeting.videomeeting.module.edp.EDPUtils;
import com.hottv.meeting.videomeeting.module.edp.data.MeetingInfo;
import com.hottv.meeting.videomeeting.module.file.activity.FolderActivity;
import com.hottv.meeting.videomeeting.module.meeting.InfoAccessImpl;
import com.hottv.meeting.videomeeting.module.meeting.MeetUtils;
import com.hottv.meeting.videomeeting.module.meeting.MeetingManager;
import com.hottv.meeting.videomeeting.module.meeting.bean.HotMessage;
import com.hottv.meeting.videomeeting.module.meeting.data.MeetInfo;
import com.hottv.meeting.videomeeting.module.meeting.data.MemSelectInfo;
import com.hottv.meeting.videomeeting.module.meeting.view.VideoAdapter;
import com.hottv.meeting.videomeeting.module.meeting.view.VideoData;
import com.hottv.meeting.videomeeting.module.white.DoCallback;
import com.hottv.meeting.videomeeting.module.white.WhiteManager;
import com.hottv.meeting.videomeeting.module.white.WhiteUtils;
import com.hottv.meeting.videomeeting.module.white.data.ItemInfo;
import com.skw.library.decoration.DividerGridItemDecoration;
import com.skw.library.focus.AbsFocusEffectView;
import com.skw.library.focus.FocusEffectViewUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;

import static com.hottv.meeting.videomeeting.common.MeetingConfig.EVENT_NAME;
import static com.hottv.meeting.videomeeting.common.MeetingConfig.MeetingContact;

/**
 * Created by chengwenqiang on 2019/7/12.
 */

public class Meeting2Activity extends Activity implements View.OnClickListener {

//    private AbsFocusEffectView absFocusEffectView;
    //大的白板背景
    private RelativeLayout mWhitePanel;
    private EditText mEditText;
    private Button mBtnEnter;
    private TextView mTxtPage;

    //大的视频会议面板
    private RelativeLayout mVideoBigPanel;

    //视频容器
    private RelativeLayout mVideoContainer;

    //聊天容器
    private RelativeLayout mMsgContainer;

   private TextView  mMsgMsg ;

   private Handler mHandler ;

//    //聊天按钮
//    private ImageView mVideoMsg;
//    //聊天按钮
//    private ImageView mMsgMsg;

    private RecyclerView  mVideoList;

//    //上传按钮
//    private Button mUpload;

    //声网引擎
    private RtcEngine mRtcEngine;

    //声网消息引擎
    private AgoraAPIOnlySignal mAgoraSigAPI;

    private  Gson mGson =new Gson();

    private Context mContext;
    //设置是否为主叫  如果是主叫
    private Boolean mIsCall = true;

    //是否可说话
    private Boolean mIsSpeak = true;

    //视频有限还是白板优先，如果是视频则视频显示在最左边，如果是
    private Boolean mVideoFirst = true;

    private String mRoomId;
    private int mUserId;


    private VideoAdapter mVideoAdapter;
    private RecyclerView mRecycleView;

    private ListView mListViewMsg;
    private MsgAdapter mMsgAdapter;

    private TextView mMeetingTime;
    private TextView mTimeCost;

    //画笔面板
    private RelativeLayout mPenColorPanel;
    private RelativeLayout mPenThickPanel;
    private TextView mMsgTips;
    private TextView mTxtColor;
    private TextView mTxtThick;
    private TextView mTxtRubber;
    private TextView mTxtTrash;
    private TextView mTxtScaleBig;
    private TextView mTxtScaleSmall;
    private TextView mTxtCloud;
    private TextView mTxtDown;
    private TextView mTxtUp;

    private ImageView mImgBlue;
    private ImageView mImgGreen;
    private ImageView mImgOrange;
    private ImageView mImgPurple;
    private ImageView mImgRed;
    private ImageView mImgYellow;
    private ImageView mImgYoung;

    private ImageView mImgBig;
    private ImageView mImgNormal;
    private ImageView mImgSmall;

    private TextView mTxtInvite;
    private TextView mTxtMsg;
    private TextView mTxtVoice;
    private TextView mTxtCamera;
    private TextView mTxtMic;
    private TextView mTxtHorn;

    private boolean mIsVoice = true;
    private boolean mIsCamera = true;
    private boolean mIsMic = true;
    private boolean mIsHorn = true;

    private Timer mTimer;
    //视屏通话声网回调
    private IRtcEngineEventHandler mRtcEventHandler =new IRtcEngineEventHandler() {
        @Override
        public void onWarning(int warn) {
            super.onWarning(warn);
        }

        @Override
        public void onError(int err) {
            super.onError(err);
        }

        @Override
        public void onStreamMessage(int uid, int streamId, byte[] data) {
            Log.i("MeetingVideo","onStreamMessage,uid:"+uid+",streamId:"+streamId+"");
        }

        @Override
        public void onStreamMessageError(int uid, int streamId, int error, int missed, int cached) {
            Log.e("MeetingVideo","onStreamMessageError,uid:"+uid+",streamId:"+streamId+",error:"+error);
        }

        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onJoinChannelSuccess(channel, uid, elapsed);
            Log.i("MeetingVideo","onJoinChannelSuccess"+",channel:"+channel+",uid:"+uid+",elapsed"+elapsed);

        }

        @Override
        public void onRejoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onRejoinChannelSuccess(channel, uid, elapsed);
            Log.i("MeetingVideo","onJoinChannelSuccess"+",channel:"+channel+",uid:"+uid+",elapsed"+elapsed);
        }

        @Override
        public void onLeaveChannel(RtcStats stats) {
            super.onLeaveChannel(stats);
            Log.i("MeetingVideo","onLeaveChannel"+",channel:"+stats.toString());
        }

        @Override
        public void onUserJoined(int uid, int elapsed) {
            super.onUserJoined(uid, elapsed);

            Log.i("MeetingVideo","onUserJoined"+",uid:"+uid+",elapsed"+elapsed);

            if(MeetingManager.getInstance().getUserNum()>=MeetingConfig.MAX_NUM)
            {
                showToast("超过视频最大人数");
                return;
            }
            //创建SurfaceView
            createSurfaceById(uid);

            //发送消息到广播
            sendMsgUserInfo();
        }

        @Override
        public void onUserOffline(int uid, int reason) {
            super.onUserOffline(uid, reason);
            Log.i("MeetingVideo","onUserOffline"+",uid:"+uid+",reason"+String.valueOf(reason));

            AgoraManager.getInstance().removeUser(uid);

            MeetingManager.getInstance().removeUserBean(uid);

            removeSurfaceById(uid);

            //更新ui
//            updateUI();
            updateAIUI(uid);
        }

        @Override
        public void onFirstRemoteAudioFrame(int uid, int elapsed) {
            super.onFirstRemoteAudioFrame(uid, elapsed);
        }
    };

    //声网信息传输 回调
    private AgoraAPI.CallBack  mAPICallBack = new AgoraAPI.CallBack() {

        @Override
        public void onLoginSuccess(int i, int i1) {
            Log.i("MeetingMsg","onLoginSuccess:"+i);

            Log.i("MeetingMsg","channelJoin meetingId:"+mRoomId);
            mAgoraSigAPI.channelJoin(mRoomId);
        }

        @Override
        public void onLogout(int i) {
            Log.i("MeetingMsg","onLogout:,i:"+i);
        }

        @Override
        public void onLoginFailed(int i) {
            Log.i("MeetingMsg","onLoginFailed:");
        }

        @Override
        public void onChannelJoined(String account) {
            Log.i("MeetingMsg","onChannelJoined:"+account);
        }

        @Override
        public void onChannelJoinFailed(String account, int uid) {
            Log.i("MeetingMsg","onChannelJoinFailed:"+account+",uid:"+uid);
        }

        @Override
        public void onChannelLeaved(String account, int uid) {
            Log.i("MeetingMsg","onChannelLeaved:"+account+",uid:"+uid);
        }

        @Override
        public void onChannelUserJoined(String account, int uid) {
            super.onChannelUserJoined(account,uid);
            Log.i("MeetingMsg","onChannelUserJoined:"+account+",uid:"+uid);
        }

        @Override
        public void onChannelUserLeaved(String account, int uid) {
            super.onChannelUserLeaved(account, uid);
            Log.i("MeetingMsg","onChannelUserLeaved:"+account+",uid:"+uid);
        }

        @Override
        public void onMessageSendError(String messageID, int ecode) {
            Log.i("MeetingMsg","onMessageSendError:"+messageID+"ecode:"+ecode);
        }

        @Override
        public void onMessageSendSuccess(String messageID) {
            Log.i("MeetingMsg","onMessageSendSuccess："+messageID);
        }

        @Override
        public void onMessageInstantReceive(final String account, int uid,final String msg) {
            Log.i("MeetingMsg", "onMessageInstantReceive  account = " + account + " uid = " + uid + " msg = " + msg);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //接收消息
                    try{
                        HotMessage msgHot = mGson.fromJson(msg,HotMessage.class);
                        handleFromMsg(msgHot,account);
                    }catch (JsonSyntaxException e)
                    {
                        Log.e("MeetingMsg","onMessageInstantReceive error:"+e.toString());
                    }
                }
            });
        }

        @Override
        public void onMessageChannelReceive(final String channelID, final String account, int uid, final String msg) {
            Log.i("MeetingMsg", "onMessageChannelReceive  account = " + account + " uid = " + uid + " msg = " + msg+",channelID:"+channelID);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try{
                        //接收消息
                        HotMessage msgHot = mGson.fromJson(msg,HotMessage.class);
                        handleFromMsg(msgHot,account);
                    }catch (JsonSyntaxException e)
                    {
                        Log.e("MeetingMsg","onMessageInstantReceive error:"+e.toString());
                    }
                }
            });
        }

        @Override
        public void onLog(String log) {
//            Log.i("MeetingMsg","onLog:"+account);
        }
    };

    private AbsFocusEffectView absFocusEffectView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeting2);
        absFocusEffectView = FocusEffectViewUtil.bindFocusEffectView(this);
        mContext = this;
        mHandler = new Handler(getMainLooper());
//        absFocusEffectView = FocusEffectViewUtil.bindFocusEffectView(this);
        initView();

        initWhitePen();

        //当view初始化ok后调用
        final View layout = findViewById(Window.ID_ANDROID_CONTENT);
        ViewTreeObserver vto = layout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }

                new Handler().postDelayed(new Runnable(){
                    public void run(){
                        initUIandEvent();
                    }
                },500);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        InfoAccessImpl.getInstance(mContext);
    }

    @Override
    protected void onDestroy() {
        InfoAccessImpl.getInstance(mContext);
        absFocusEffectView.destory();
        deInitUIandEvent();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown (int keyCode, KeyEvent event)
    {
        Log.i(MeetingConfig.TAG,"dispatchKeyEvent key:"+keyCode);
        if(keyCode == MeetingConfig.key_back_action){
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("退出视频会议");
            builder.setMessage("是否退出视频会议？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    int broadcastUserId = MeetingManager.getInstance().getMeetingBean().getMeetingUserId();
                    if(broadcastUserId==mUserId)
                    {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 200);

                        HotMessage hotMsg =new HotMessage();
                        hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_QUIT);
                        String hotMsgContent = mGson.toJson(hotMsg);
                        Log.i(MeetingConfig.TAG,"会议结束:"+hotMsgContent);
                        mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
//                        showToast("会议正在结束中");
                    }
                    else
                    {
                        finish();
                    }
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.create().show();
        }
        else if(keyCode == MeetingConfig.key_channel_up_action)
        {

        }
        else if(keyCode == MeetingConfig.key_channel_down_action)
        {

        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent bundle) {
        super.onActivityResult(requestCode, resultCode, bundle);
        Log.i(MeetingConfig.TAG, "requestCode: " + requestCode + "; resultCode: " + resultCode);
        if(requestCode==1)
        {
            if (resultCode == RESULT_OK) {
                String filePath  = bundle.getStringExtra("file");
                Log.i(MeetingConfig.TAG, "upLoad White filePath: " + filePath);
//            Toast.makeText(mContext,"正在加载ppt中，预计耗时15s,请耐心等待",Toast.LENGTH_LONG).show();
                showToast("正在加载ppt中，预计耗时15s,请耐心等待");
                upLoadWhite(MeetingUtils.storage_url,filePath);
            }
        }
        else if(requestCode==2)
        {
            if(bundle!=null)
            {
                String data  = bundle.getStringExtra(MeetingContact);
                if(data!=null)
                {
                    Log.i(MeetingConfig.TAG, "data: " + data);
                }
            }

            if (resultCode == RESULT_OK) {
//            Toast.makeText(mContext,"正在加载ppt中，预计耗时15s,请耐心等待",Toast.LENGTH_LONG).show();
                showToast("已经成功邀请好友");
//                upLoadWhite(MeetingUtils.storage_url,filePath);
            }
            else
            {
                //获取通讯录失败
                Log.i(MeetingConfig.TAG, "获取通讯录失败: ");
            }
        }

    }

    private void upLoadWhite(String url,String filePath)
    {
        if(mRoom!=null)
        {
            WhiteUtils.getPNG(url,filePath, new DoCallback() {

                @Override
                public void onSuccess(String info) {

                    Log.i(MeetingConfig.TAG,"onSuccess!!!!!!!!!!");
                    showToast("全部加载完成！！！");
                    Scene[] scenes = WhiteManager.getInstance().getLeftScene();
                    if(scenes!=null)
                    {
                        mRoom.putScenes(MeetingConfig.SCENE_DIR,scenes,Integer.MAX_VALUE);
                    }
                }

                @Override
                public void onFailor(String info) {

                }

                @Override
                public void onProcess(String info) {

                    Log.i(MeetingConfig.TAG,"process!!!!!!!!!!");
                    showToast("努力为您显示中！！！");
                    Scene[] scenes = WhiteManager.getInstance().getInitScene();
                    if(scenes!=null)
                    {
                        Log.i(MeetingConfig.TAG,"num:"+scenes.length);
                        mRoom.putScenes(MeetingConfig.SCENE_DIR,scenes,0);
                        mRoom.setScenePath(MeetingConfig.SCENE_DIR+"/"+String.valueOf(0));

                        ItemInfo pptInfo =  WhiteManager.getInstance().getCurrentPageInfo();

                        double scale = 1.0d;
                        if(pptInfo!=null&&pptInfo.height>0&&pptInfo.width>0)
                        {
                            if((pptInfo.height/(double)pptInfo.width) >(MeetingConfig.ppt_heigh/(double)MeetingConfig.ppt_width))
                            {
                                scale = (double) (MeetingConfig.ppt_heigh) /pptInfo.height;
                                Log.i(MeetingConfig.TAG,"1scale pptconfig:"+MeetingConfig.ppt_heigh+",ppt:"+pptInfo.height);
                            }
                            else
                            {
                                scale = (double) (MeetingConfig.ppt_width)/pptInfo.width;
                                Log.i(MeetingConfig.TAG,"2scale pptconfig:"+MeetingConfig.ppt_width+",ppt:"+pptInfo.width);

                            }
                            scale = scale* 0.95;
                            Log.i(MeetingConfig.TAG,"scale :"+scale);
                            WhiteUtils.zoomChange(mRoom,scale,true);
//                            mRoom.zoomChange(scale);
                            if(mSamllRoom!=null)
                            {
//                                mSamllRoom.zoomChange(scale*0.22);
                                WhiteUtils.zoomChange(mSamllRoom,scale*0.25,true);
                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    int current = WhiteManager.getInstance().getCurrentPage()+1;
                                    int totoal = WhiteManager.getInstance().getTotalPage();
                                    mTxtPage.setText("当前页："+current+"/"+totoal);
                                }
                            });
                        }
                    }
                }
            });
        }else
        {
            showToast("白板未初始化，请稍等");
        }
    }


    //初始化界面 找到对应的应用
    private void initView()
    {
        mWhitePanel = (RelativeLayout) findViewById(R.id.ppt_panel);
        mWhitePanel.setVisibility(View.INVISIBLE);

//        MeetUtils.addClickNormalBox(mWhitePanel,true,false);

        mTxtPage = (TextView) findViewById(R.id.txt_page);
        mTxtPage.setText("当前页：0/0");

        mBtnEnter = (Button) findViewById(R.id.btn_enter) ;
        MeetUtils.addClickNormalBox(mBtnEnter,true,false);

        mEditText = (EditText) findViewById(R.id.edit_msg);
        MeetUtils.addClickNormalBox(mEditText,true,false);
        mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus)
                {
                    mEditText.setText("");
                }
                else
                {
                    mEditText.setText("请输入您想说的话");
                }
            }
        });
        mVideoBigPanel = (RelativeLayout) findViewById(R.id.video_big_panel);
        mVideoBigPanel.setVisibility(View.VISIBLE);

        mMeetingTime = (TextView) findViewById(R.id.txt_meeting_time);
        mTimeCost = (TextView) findViewById(R.id.txt_time_cost);

        mVideoContainer = (RelativeLayout) findViewById(R.id.video_container_panel);
        mMsgContainer = (RelativeLayout) findViewById(R.id.msg_container_panel);

        mMsgMsg = (TextView) findViewById(R.id.txt_chat_head);
        MeetUtils.addClickNormalBox(mMsgMsg,true,false);
        mMsgMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVideoContainer.setVisibility(View.VISIBLE);
                mMsgContainer.setVisibility(View.INVISIBLE);

                mTxtMsg.requestFocus();

                List<MsgItem> msgList = AgoraManager.getInstance().getMsgList();
                AgoraManager.getInstance().setReadNum(msgList.size());
                mMsgTips.setVisibility(View.INVISIBLE);
            }
        });

        mVideoList = (RecyclerView) findViewById(R.id.recycler_view);

//        mUpload = (Button) findViewById(R.id.btn_upload);
////        mUpload.setTag(R.id.focus_type, AbsFocusEffectView.FocusType.FOCUS_NORMAL);
////        mUpload.setTag(R.id.focus_type_is_translate, true);
////        mUpload.setTag(R.id.focus_type_is_scale_anim, true);
//        mUpload.setFocusable(true);
//        mUpload.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(Meeting2Activity.this,FolderActivity.class);
//                startActivityForResult(intent,1);
//            }
//        });

        //聊天信息列表
        mListViewMsg = (ListView) findViewById(R.id.list_view_msg);
        List<MsgItem> msgList = new ArrayList<>();
        mMsgAdapter = new MsgAdapter(mContext,msgList);
        mListViewMsg.setAdapter(mMsgAdapter);
        mListViewMsg.setSelection(ListView.FOCUS_DOWN);

        mRecycleView = (RecyclerView) findViewById(R.id.recycler_view);
        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this );
        layoutManager.setOrientation(OrientationHelper. VERTICAL);
        mRecycleView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的

        mRecycleView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(13,10,13,10);
            }
        });

        mVideoAdapter = new VideoAdapter(this, new ArrayList<VideoData>(), new VideoAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int tag =  (int )view.getTag();
                Log.i(MeetingConfig.TAG,"tag:"+tag+",position:"+position);
                if(tag == MeetingConfig.TYPE_INVITE)
                {

                }
                else if(tag ==MeetingConfig.TYPE_WHITE)
                {
                    if(mSamllRoom==null)
                    {
                        showToast("白板初始化未完成，请稍等！！！");
                        return;
                    }

                    mVideoFirst = false;
                    updateUI();

                }
                else if(tag==MeetingConfig.TYPE_VIDEO)
                {
                    if(position==0)
                    {
                        mVideoFirst = true;
                        updateUI();
                    }
                    else
                    {
                        //请求发送设置主播
                        requestSetBroastcast(position);
                    }
                }
            }
        });

        mRecycleView.setAdapter(mVideoAdapter);
    }

    private void initWhitePen()
    {
        mPenColorPanel = (RelativeLayout) findViewById(R.id.pen_panel_bg);
        mPenThickPanel = (RelativeLayout) findViewById(R.id.thickness_panel_bg);

        mTxtColor = (TextView) findViewById(R.id.txt_pen);
        mTxtColor.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtColor,true,false);

        mTxtThick = (TextView) findViewById(R.id.txt_thickness);
        mTxtThick.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtThick,true,false);

        mTxtRubber = (TextView) findViewById(R.id.txt_eraser);
        mTxtRubber.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtRubber,true,false);

        mTxtTrash = (TextView) findViewById(R.id.txt_garbage);
        mTxtTrash.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtTrash,true,false);

        mTxtScaleBig = (TextView) findViewById(R.id.txt_scale_big);
        mTxtScaleBig.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtScaleBig,true,false);

        mTxtScaleSmall = (TextView) findViewById(R.id.txt_scale_small);
        mTxtScaleSmall.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtScaleSmall,true,false);

        mTxtDown = (TextView) findViewById(R.id.txt_down);
        mTxtDown.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtDown,true,false);
        mTxtUp = (TextView) findViewById(R.id.txt_up);
        mTxtUp.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtUp,true,false);

        mTxtCloud = (TextView) findViewById(R.id.txt_cloud);
        mTxtCloud.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtCloud,true,false);

        mTxtInvite = (TextView) findViewById(R.id.txt_invite);
        mTxtInvite.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtInvite,true,false);
        mTxtInvite.setNextFocusLeftId(R.id.txt_up);


        mTxtMsg = (TextView) findViewById(R.id.txt_chat);
        mTxtMsg.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtMsg,true,false);
        mMsgTips = (TextView) findViewById(R.id.txt_chat_tips);
        mMsgTips.setVisibility(View.INVISIBLE);
        MeetUtils.addClickNormalBox(mMsgTips,true,false);

        mTxtVoice = (TextView) findViewById(R.id.txt_voice);
        mTxtVoice.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtVoice,true,false);

        mTxtCamera = (TextView) findViewById(R.id.txt_camera);
        mTxtCamera.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtCamera,true,false);
        mTxtCamera.setNextFocusLeftId(R.id.txt_up);

        mTxtMic = (TextView) findViewById(R.id.txt_mic);
        mTxtMic.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtMic,true,false);

        mTxtHorn = (TextView) findViewById(R.id.txt_horn);
        mTxtHorn.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mTxtHorn,true,false);


        mImgBig = (ImageView) findViewById(R.id.thickness_big);
        mImgBig.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgBig,true,false);
        mImgNormal = (ImageView) findViewById(R.id.thickness_small);
        mImgNormal.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgNormal,true,false);
        mImgSmall = (ImageView) findViewById(R.id.thickness_thiny);
        mImgSmall.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgSmall,true,false);

        mImgBlue = (ImageView) findViewById(R.id.pen_color_blue);
        mImgBlue.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgBlue,true,false);
        mImgGreen = (ImageView) findViewById(R.id.pen_color_green);
        mImgGreen.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgGreen,true,false);
        mImgOrange = (ImageView) findViewById(R.id.pen_color_orange);
        mImgOrange.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgOrange,true,false);
        mImgPurple = (ImageView) findViewById(R.id.pen_color_purple);
        mImgPurple.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgPurple,true,false);
        mImgRed = (ImageView) findViewById(R.id.pen_color_red);
        mImgRed.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgRed,true,false);
        mImgYellow = (ImageView) findViewById(R.id.pen_color_yellow);
        mImgYellow.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgYellow,true,false);
        mImgYoung = (ImageView) findViewById(R.id.pen_color_young);
        mImgYoung.setOnClickListener(this);
        MeetUtils.addClickNormalBox(mImgYoung,true,false);
    }

    @Override
    public void onClick(View v) {
//        if(mRoom==null)
//        {
//            showToast("白板未初始化，请耐心等候");
//            return;
//        }

       switch (v.getId())
       {
           case R.id.txt_pen:
               mPenColorPanel.setVisibility(View.VISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mImgPurple.requestFocus();
               break;
           case R.id.txt_thickness:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.VISIBLE);
               mImgNormal.requestFocus();
               break;
           case R.id.txt_eraser:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               WhiteUtils.eraser(mRoom);
               break;

           case R.id.txt_garbage:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               WhiteUtils.cleanScene(mRoom);
               break;

           case R.id.txt_scale_big:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);

               WhiteUtils.zoomChange(mRoom, new Promise<Number>() {
                   @Override
                   public void then(Number number) {
                       mRoom.zoomChange(number.doubleValue()*1.1);
                   }

                   @Override
                   public void catchEx(SDKError sdkError) {

                   }
               });
               break;

           case R.id.txt_scale_small:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               WhiteUtils.zoomChange(mRoom, new Promise<Number>() {
                   @Override
                   public void then(Number number) {
                       mRoom.zoomChange(number.doubleValue()*0.9);
                   }

                   @Override
                   public void catchEx(SDKError sdkError) {

                   }
               });
               break;

           case R.id.txt_down:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               handleDown();
               break;
           case R.id.txt_up:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               handleUp();
               break;
           case R.id.txt_cloud:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               Intent intent = new Intent(Meeting2Activity.this,FolderActivity.class);
               startActivityForResult(intent,1);
               break;

           case R.id.thickness_big:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtThick.requestFocus();
               WhiteUtils.setStrokeWidth(mRoom,12);
               break;

           case R.id.thickness_small:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtThick.requestFocus();
               WhiteUtils.setStrokeWidth(mRoom,6);
               break;

           case R.id.thickness_thiny:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtThick.requestFocus();
               WhiteUtils.setStrokeWidth(mRoom,2);
               break;


           case R.id.pen_color_blue:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_blue));
               break;

           case R.id.pen_color_green:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_green));
               break;

           case R.id.pen_color_orange:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_orange));
               break;

           case R.id.pen_color_purple:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_purple));
               break;

           case R.id.pen_color_red:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_red));
               break;

           case R.id.pen_color_yellow:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_yellow));
               break;

           case R.id.pen_color_young:
               mPenColorPanel.setVisibility(View.INVISIBLE);
               mPenThickPanel.setVisibility(View.INVISIBLE);
               mTxtColor.requestFocus();
               WhiteUtils.setColor(mRoom,WhiteUtils.getColor(mContext,R.color.color_young));
               break;
           case R.id.txt_invite:
               //添加用户
               if(MeetingManager.getInstance().getUserNum()>=MeetingConfig.MAX_NUM)
               {
                   showToast("超过视频最大人数");
                   return;
               }

               //邀请好友
               Intent intentLauncher = new Intent();
               intentLauncher.putExtra(MeetingContact, "data");
               ComponentName comp = new ComponentName("com.hotwater.waterlauncher","com.hotwater.waterlauncher.activity.MainActivity");
               intentLauncher.setComponent(comp);
               intentLauncher.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
               startActivityForResult(intentLauncher,2);
               break;
           case R.id.txt_chat:
               mVideoContainer.setVisibility(View.INVISIBLE);
               mMsgContainer.setVisibility(View.VISIBLE);
               mMsgMsg.requestFocus();
               break;
           case R.id.txt_voice:
               if(mIsVoice)
               {
                   sendCanVoice(HotMessage.MESSAGE_TYPE_SHUT_UP);
                   mTxtVoice.setBackgroundResource(R.drawable.fun_btn_horn_speak_bg);
               }
               else
               {
                   sendCanVoice(HotMessage.MESSAGE_TYPE_SPEAK);
                   mTxtVoice.setBackgroundResource(R.drawable.fun_btn_horn_shut_up_bg);
               }
               mIsVoice = !mIsVoice;
               break;
           case R.id.txt_camera:

               if(mIsCamera)
               {
                   enableVideo(false);
                   mTxtCamera.setBackgroundResource(R.drawable.fun_btn_camera_shut_bg);
               }
               else
               {
                   enableVideo(true);
                   mTxtCamera.setBackgroundResource(R.drawable.fun_btn_camera_open_bg);
               }
               mIsCamera = !mIsCamera;

               break;
           case R.id.txt_mic:
               if(mIsMic)
               {
                   enableAudio(false);
                   mTxtMic.setBackgroundResource(R.drawable.fun_btn_mic_shut_bg);
               }
               else
               {
                   enableAudio(true);
                   mTxtMic.setBackgroundResource(R.drawable.fun_btn_mic_open_bg);
               }
               mIsMic = !mIsMic;
               break;
           case R.id.txt_horn:
               if(mIsHorn)
               {
                   MeetUtils.enableLocalAudio(mContext,false);
                   mTxtHorn.setBackgroundResource(R.drawable.fun_btn_horn_speak_bg);

               }
               else
               {
                   MeetUtils.enableLocalAudio(mContext,true);
                   mTxtHorn.setBackgroundResource(R.drawable.fun_btn_horn_shut_up_bg);
               }
               mIsHorn = !mIsHorn;
               break;
       }
    }

    private void requestSetBroastcast(final int pos)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                List<VideoData>  videoList = MeetUtils.getVideoDataList(mUserId,mVideoFirst);
                final  VideoData data = videoList.get(pos);

                //如果本机是会议创建者
                final HotMessage.MeetingBean meetingBean= MeetingManager.getInstance().getMeetingBean();
                if(meetingBean==null)
                {
                    Log.e(MeetingConfig.TAG,"MeetingManager meetingBean is null !!!!!!!!!!!!!!!");
                    return;
                }
                if(mUserId ==meetingBean.getMeetingUserId())
                {
                    //如果点击的是自己，并且自己已经是主播
                    if(data.userId==mUserId && mUserId==MeetingManager.getInstance().getBroadcastBean().getBroadcastUserId())
                    {
                        Log.i(MeetingConfig.TAG,"您自己已经是主播，无需请求为主播");
                        showToast("您自己已经是主播，无需请求为主播");
                        return;
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    final HotMessage.UserBean userBean = MeetingManager.getInstance().getUserBean(data.userId);
                    builder.setTitle("主播设置");
                    builder.setMessage("是否将"+userBean.getNickname()+"设置为主播？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            HotMessage hotMsg = new HotMessage();
                            hotMsg.setUser(MeetUtils.getUserBean(mContext));
                            hotMsg.setMeeting(meetingBean);

                            //需要将即将成为主播的任务信息 填充进主播
                            HotMessage.BroadcastBean bean = new HotMessage.BroadcastBean();
                            bean.setBroadcastNickname(userBean.getNickname());
                            bean.setBroadcastUserId(userBean.getUserId());
                            bean.setBroadcastId(userBean.getHottvId());
                            bean.setBroadcastAvatar("无");
                            hotMsg.setBroadcast(bean);

                            //如果是创建者想把自己设置为主播则直接发广播
                            if(data.userId==mUserId)
                            {
                                hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_CHANGE_BROASTCAST);

                                String hotMsgContent = mGson.toJson(hotMsg);

                                Log.i(MeetingConfig.TAG,"发送主播变更通知:"+hotMsgContent);
                                mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
                            }
                            else
                            {
                                hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_SET_BROASTCAST);
                                String hotMsgContent = mGson.toJson(hotMsg);
                                Log.i(MeetingConfig.TAG,"是否将xxx设置为主播:"+hotMsgContent);
                                //想目标发送请求设置为主播
                                mAgoraSigAPI.messageInstantSend(String.valueOf(data.userId),0,hotMsgContent,"");
                            }
                        }
                    });

                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builder.create().show();
                }
                else
                {
                    if(data.userId == mUserId)
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                        builder.setTitle("主播设置");
                        builder.setMessage("是否请求将自己设置为主播？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

                                HotMessage hotMsg = new HotMessage();
                                hotMsg.setUser(MeetUtils.getUserBean(mContext));
                                HotMessage.MeetingBean meetingBean = MeetingManager.getInstance().getMeetingBean();
                                hotMsg.setMeeting(meetingBean);

                                //需要将即将成为主播的任务信息 填充进主播
                                HotMessage.UserBean userBean = MeetingManager.getInstance().getUserBean(data.userId);
                                HotMessage.BroadcastBean bean = new HotMessage.BroadcastBean();
                                bean.setBroadcastNickname(userBean.getNickname());
                                bean.setBroadcastUserId(userBean.getUserId());
                                bean.setBroadcastId(userBean.getHottvId());
                                bean.setBroadcastAvatar("无");
                                hotMsg.setBroadcast(bean);

                                hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_REQUEST_BROASTCAST);

                                String hotMsgContent = mGson.toJson(hotMsg);
                                Log.i(MeetingConfig.TAG,"是否请求将自己设置为主播:"+hotMsgContent);
                                //向会议创建者请求自己为主播
                                mAgoraSigAPI.messageInstantSend(String.valueOf(meetingBean.getMeetingUserId()),0,hotMsgContent,"");
                            }
                        });

                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                    else
                    {
                        showToast("无权限设置主播！！！");
                    }
                }
            }
        });
    }


    private  int mTimeSpan = 0;
    private void showTimeCost()
    {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTimeCost.setText(MeetUtils.formatTimeS(mTimeSpan));
                        mTimeSpan = mTimeSpan+1;
                    }
                });
            }
        },0,1000);

    }
    //界面加载完成后 初始化
    private void initUIandEvent()
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                showTimeCost();

                mRtcEngine = AgoraManager.getInstance().initEngine(mContext, mRtcEventHandler);
                AgoraManager.getInstance().clearUserMap();

                //初始化消息
                mAgoraSigAPI = AgoraManager.getInstance().initSigSdk(mContext);

                mMeetingTime.setText("开始时间："+MeetUtils.getCurrentTime());
                //设置主叫页面
                Intent intent = getIntent();
                String data = intent.getStringExtra(MeetingConfig.MeetingDATA);
                //主叫页面
                if(!TextUtils.isEmpty(data))
                {
                    mIsCall =true;
                    Log.i(MeetingConfig.TAG,"data:"+data);


//                    MeetingManager.getInstance().AddMem(mGson.fromJson(data,MeetInfo.class));

                    HotMessage.UserBean userBean = MeetUtils.getUserBean(mContext);
                    //设置会议创建者
                    HotMessage.MeetingBean meetingBean = new HotMessage.MeetingBean();
                    meetingBean.setMeetingUserId(userBean.getUserId());
                    meetingBean.setMeetingId(userBean.getHottvId());
                    meetingBean.setMeetingNickname(userBean.getNickname());
                    meetingBean.setMeetingAvatar("无");
                    MeetingManager.getInstance().setMeetingBean(meetingBean);
                    //设置会议主播
                    HotMessage.BroadcastBean broadcastBean = new HotMessage.BroadcastBean();
                    broadcastBean.setBroadcastAvatar("无");
                    broadcastBean.setBroadcastId(userBean.getHottvId());
                    broadcastBean.setBroadcastUserId(userBean.getUserId());
                    broadcastBean.setBroadcastNickname(userBean.getNickname());
                    MeetingManager.getInstance().setBroadcastBean(broadcastBean);

                    MeetingManager.getInstance().addUserBean(userBean);

                    //请求数据
                    MeetingUtils.getMeetingInfo(mContext, new DoCallback() {
                        @Override
                        public void onSuccess(String info) {
                            // 推送发送数据
                            Log.i(MeetingConfig.TAG,"pushMsgMeetingMem onSuccess meetingId:"+info);
//                            MeetingUtils.pushMsgMeetingMem(mContext,info);
                            // 初始化页面
                            initCallView(info);
                        }

                        @Override
                        public void onFailor(String info) {
                            showToast("创建会议失败");
                        }

                        @Override
                        public void onProcess(String info) {
                        }
                    });
                }
                else   //被叫页面
                {
                    mIsCall =false;
                    String incallData = intent.getStringExtra(MeetingConfig.MeetingDATA_Incall);
                    Log.i(MeetingConfig.TAG,"incall data:"+incallData);
                    MeetingInfo info = mGson.fromJson(incallData,MeetingInfo.class);

                    final String meetingId = info.content.meetingId;

                    HotMessage.UserBean userBean = MeetUtils.getUserBean(mContext);
                    MeetingManager.getInstance().addUserBean(userBean);
                    MeetingUtils.joinMeeting(mContext, meetingId, new DoCallback() {
                        @Override
                        public void onSuccess(String info) {
                            //开启被叫页面
                            initInCallView(meetingId);
                        }

                        @Override
                        public void onFailor(String info) {
                            showToast("创建会议失败");
                        }

                        @Override
                        public void onProcess(String info) {

                        }
                    });
                }
            }
        });
    }

    //界面销毁时调用
    private void deInitUIandEvent()
    {
        Log.i(MeetingConfig.TAG,"------deInitUIandEvent--------------------");
        if(mTimer!=null)
        {
            mTimer.cancel();
        }
        mRoomBigInit = false;
        mRoomSmallInit = false;
        //退出频道
        if (mRtcEngine != null) {
            mRtcEngine.leaveChannel();

            mRtcEngine=null;
        }
        Log.i(MeetingConfig.TAG,"------退出频道--------------------");
        AgoraManager.getInstance().destoryRTC();

        if(mAgoraSigAPI!=null)
        {
            mAgoraSigAPI.channelLeave(mRoomId);
            mAgoraSigAPI =null;
        }

        Log.i(MeetingConfig.TAG,"------退出消息--------------------");
        AgoraManager.getInstance().lougout();

        //清除列表
        AgoraManager.getInstance().clearMsg();

        mUuid = "";

        if(mRoom!=null)
        {
            mRoom.disconnect();
            mRoom =null;
        }
        Log.i(MeetingConfig.TAG,"------退出房间--------------------");
        MeetingManager.getInstance().destroy();
    }

    //处理被叫
    private void initInCallView(final String meetingId)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRoomId = meetingId;
                mUserId = Integer.parseInt(EDPUtils.edp_devices_Id) ;

                //主叫中 设置 userid为 观众
                AgoraManager.getInstance().setUserType(mUserId,MeetingConfig.AUDIENCE_TYPE);

                //处理声网消息
                initEngineMsg();

                //设置声网配置文件 如果自己是主播 则用最高等级的视频编解码方案
//                initEngineConfig(MeetingConfig.BROADCASTER_TYPE,MeetingConfig.AUDIENCE_PROFILE_IDX);

                updateUI();
            }
        });
    }

    //处理主叫页面
    private void initCallView(final  String meetingId)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRoomId = meetingId;
                mUserId = Integer.parseInt(EDPUtils.edp_devices_Id) ;

                //主叫中 设置 userid为 主播
                AgoraManager.getInstance().setUserType(mUserId,MeetingConfig.BROADCASTER_TYPE);

                //处理声网消息
                initEngineMsg();

                //设置声网配置文件 如果自己是主播 则用最高等级的视频编解码方案
//                initEngineConfig(MeetingConfig.BROADCASTER_TYPE,MeetingConfig.DEFAULT_PROFILE_IDX);

                updateUI();
            }
        });
    }

    //初始化消息，登录消息、设置消息回调
    private void initEngineMsg()
    {
        Log.i(MeetingConfig.TAG,"handleMsg login:mRoomId"+mRoomId+",mUserId:"+mUserId);
        String appId = mContext.getString(R.string.agora_app_id);
        String account = EDPUtils.edp_devices_Id;
        mAgoraSigAPI.login2(appId,account,"_no_need_token",0,"",2,1);
        mAgoraSigAPI.callbackSet(mAPICallBack);
    }

    //设置引擎配置
    private void initEngineConfig(final int cRole,final int pref) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                VideoEncoderConfiguration.VideoDimensions dimension = MeetingConfig.VIDEO_DIMENSIONS[pref];

                mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(dimension,
                        VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_24,
                        VideoEncoderConfiguration.STANDARD_BITRATE,
                        VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE));
                mRtcEngine.setClientRole(cRole);
            }
        });

    }

    //处理主播的UI
    private void handleUI(Boolean videoFirst)
    {
        if(videoFirst)
        {
            mVideoBigPanel.setVisibility(View.VISIBLE);
            mWhitePanel.setVisibility(View.INVISIBLE);

            mTxtInvite.setNextFocusLeftId(0);
            mTxtCamera.setNextFocusLeftId(0);
        }
        else
        {
            mVideoBigPanel.setVisibility(View.INVISIBLE );
            mWhitePanel.setVisibility(View.VISIBLE);

            mTxtInvite.setNextFocusLeftId(R.id.txt_up);
            mTxtCamera.setNextFocusLeftId(R.id.txt_up);

        }

        mVideoContainer.setVisibility(View.VISIBLE);
        mMsgContainer.setVisibility(View.INVISIBLE);

        int broadcastUserId = MeetingManager.getInstance().getMeetingBean().getMeetingUserId();
        if(broadcastUserId==mUserId) {
            mTxtVoice.setVisibility(View.VISIBLE);
        }
        else{
            mTxtVoice.setVisibility(View.INVISIBLE);
        }
    }

    //处理声网音视频本地
    private void handleBroadcastUI(Boolean videoFirst)
    {
       int broadcastUserId = AgoraManager.getInstance().getBroastcastId();
       //如果没有主播，则自己启动为被叫
       if(broadcastUserId==0)
       {
           initEngineConfig(MeetingConfig.BROADCASTER_TYPE,MeetingConfig.AUDIENCE_PROFILE_IDX);
           SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(mUserId);
           if(surfaceView==null)
           {
               surfaceView = RtcEngine.CreateRendererView(getApplicationContext());
               MeetingManager.getInstance().insertSurfaceView(mUserId,surfaceView);

               mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, mUserId));
               mRtcEngine.enableVideo();
               mRtcEngine.startPreview();
               mRtcEngine.joinChannel(null,mRoomId,"OpenLive",mUserId);
           }

           return;
       }

        //如果不是主播，则将远程主播流设置为高清，本地编码流设置为低 ，如果是主播则设置本地编码流为高
        if(mUserId!=broadcastUserId)
        {
//            mRtcEngine.setRemoteVideoStreamType(broadcastUserId, Constants.VIDEO_STREAM_HIGH);
            mRtcEngine.setRemoteVideoStreamType(broadcastUserId, Constants.VIDEO_STREAM_HIGH);
            initEngineConfig(MeetingConfig.BROADCASTER_TYPE,MeetingConfig.AUDIENCE_PROFILE_IDX);
        }
        else
        {
            initEngineConfig(MeetingConfig.BROADCASTER_TYPE,MeetingConfig.DEFAULT_PROFILE_IDX);
        }

        SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(broadcastUserId);
        if(surfaceView==null)
        {
            surfaceView = RtcEngine.CreateRendererView(getApplicationContext());
            MeetingManager.getInstance().insertSurfaceView(mUserId,surfaceView);
            if(videoFirst)
            {
                mVideoBigPanel.removeAllViews();
                AgoraUtils.checkSurfaceView(surfaceView);
                mVideoBigPanel.addView(surfaceView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            }

            mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, mUserId));
            mRtcEngine.startPreview();
            mRtcEngine.joinChannel(null,mRoomId,"OpenLive",mUserId);
        }
        else
        {
            if(videoFirst)
            {
                mVideoBigPanel.removeAllViews();
                AgoraUtils.checkSurfaceView(surfaceView);
                mVideoBigPanel.addView(surfaceView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            }
        }
    }

    //处理右边视频列表
    private void handleVideoList(Boolean videoFirst)
    {
        List<VideoData>  videoList = MeetUtils.getVideoDataList(mUserId,videoFirst);
        mVideoAdapter.setList(videoList);
    }

    //处理白板
    private void handleWhite(Boolean videoFirst) {

        if (videoFirst) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    WhiteBroadView whiteView = mVideoAdapter.getWhitePanel();
                    if (whiteView == null) {
                        Log.i(MeetingConfig.TAG, "------whiteView----null---------");
                    } else {
                        joinRoomSmall(whiteView,MeetingUtils.white_uuid, MeetingUtils.white_roomtoken, false, 0.22);
                    }
                }
            }, 200);
        } else {
            WhiteBroadView whiteView = (WhiteBroadView)mWhitePanel.findViewById(R.id.white_content);
//            MeetUtils.addClickNormalBox(whiteView,true,false);
            joinRoomBig(whiteView,MeetingUtils.white_uuid, MeetingUtils.white_roomtoken, true, 1.0);
        }
    }

    private boolean mRoomBigInit = false;
    private void joinRoomBig(final WhiteBroadView whiteView, String uuid, String rooomToken, final boolean isWrite, final double scale)
    {
        if(!mRoomBigInit || (uuid!=mUuid))
        {
            joinRoom(whiteView, uuid, rooomToken, isWrite, scale);
            mRoomBigInit = true;
        }
    }

    private boolean mRoomSmallInit = false;
    private void joinRoomSmall(final WhiteBroadView whiteView, String uuid, String rooomToken, final boolean isWrite, final double scale)
    {
        if(!mRoomSmallInit || (uuid!=mUuid))
        {
            joinRoom(whiteView, uuid, rooomToken, isWrite, scale);
            mRoomSmallInit = true;
        }
    }

    private String mUuid="";
    private Room mRoom;

    private Room mSamllRoom;
    private void joinRoom(final WhiteBroadView whiteView, String uuid, String rooomToken, final boolean isWrite, final double scale)
    {
        mUuid = uuid;

        Log.i(MeetingConfig.TAG,"join room,uuid:"+mUuid+",roomToken:"+rooomToken);
        WhiteUtils.joinRoom(mContext, mUuid, rooomToken, whiteView, new Promise<Room>() {
            @Override
            public void then(Room room) {
                Log.i(MeetingConfig.TAG,"broastcaseter join in room success");
                mRoom = room;
                mRoom.addMagixEventListener(EVENT_NAME, new EventListener() {
                    @Override
                    public void onEvent(EventEntry eventEntry) {
                        Log.i(MeetingConfig.TAG,"customEvent payload: " + eventEntry.getPayload().toString());
                    }
                });

                //如果是创建者则清空白板
                int broadcastUserId = MeetingManager.getInstance().getMeetingBean().getMeetingUserId();
                if(broadcastUserId==mUserId)
                {
                    Log.i(MeetingConfig.TAG,"是主播，白板开始清空");
                    WhiteUtils.cleanScene(mRoom);
                }
                else
                {
                    Log.i(MeetingConfig.TAG,"不是主播，白板开始不清空");
                }

                if(isWrite)
                {
                    WhiteUtils.disableReadonly(mRoom);
                    WhiteUtils.broadcast(mRoom);
                }
                else
                {
                    mSamllRoom = room;
                    WhiteUtils.readonly(mRoom);
                }

                WhiteUtils.zoomChange(mRoom,scale,false);
            }

            @Override
            public void catchEx(SDKError sdkError) {
                Log.e(MeetingConfig.TAG,"白板初始化失败："+sdkError.getJsStack());
                mRoomBigInit = false;
                mRoomSmallInit = false;
                mUuid="";
                showToast("白板初始化化失败，再次初始化中！！！！ ");
                handleWhite(mVideoFirst);

            }
        });
    }

    public void onSendMsg(View view)
    {
        if(mAgoraSigAPI!=null)
        {
            String msgStr = mEditText.getText().toString();
            if(TextUtils.isEmpty(msgStr))
            {
                showToast("请输入文字");
                return;
            }

            mMsgAdapter.setList(AgoraManager.getInstance().getMsgList());
            mEditText.setText("");

            String msgJson = mGson.toJson(MeetUtils.getMsgMessage(this,msgStr)) ;

            Log.i(MeetingConfig.TAG,"onSendMsg:"+msgJson);
            mAgoraSigAPI.messageChannelSend(mRoomId,msgJson,"");
        }
    }

    //处理消息
    private void handleFromMsg(final HotMessage msgHot,final String account)
    {
        //处理聊天消息

        if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_MESSAGE)
        {
            AgoraManager.getInstance().addMsgItem(String.valueOf(msgHot.getUser().getNickname()),msgHot.getContent());
            List<MsgItem> msgList = AgoraManager.getInstance().getMsgList();
            mMsgAdapter.setList(msgList);
            if(mMsgContainer!=null && mMsgContainer.getVisibility() ==View.VISIBLE)
            {
                AgoraManager.getInstance().setReadNum(msgList.size());
            }
            else
            {
                int readNum = AgoraManager.getInstance().getReadNum();
                int unReadNum = msgList.size()-readNum;
                if(unReadNum>0)
                {
                    mMsgTips.setVisibility(View.VISIBLE);
                    mMsgTips.setText(String.valueOf(unReadNum));
                }
                else
                {
                    mMsgTips.setVisibility(View.INVISIBLE);
                }
            }
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_SET_BROASTCAST)
        {
            //如果需要设置的主播为自己则处理，否则不处理
//            if(msgHot.getBroadcast().getBroadcastUserId()==mUserId)
            if(msgHot.getBroadcast().getBroadcastId().equals(MeetingUtils.getHottvId(this)))
            {
                final String fromUserId =String.valueOf(msgHot.getUser().getUserId()) ;
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("主播设置");
                String nickName =  msgHot.getUser().getNickname();
                builder.setMessage(nickName +"将您设置为主播,是否同意？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        HotMessage hotMsg = new HotMessage();
                        HotMessage.UserBean userBean = MeetUtils.getUserBean(mContext);
                        hotMsg.setUser(userBean);
                        hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());

                        //需要将即将成为主播的任务信息 填充进主播
                        HotMessage.BroadcastBean broadBean =new HotMessage.BroadcastBean();
                        broadBean.setBroadcastAvatar("无");
                        broadBean.setBroadcastId(userBean.getHottvId());
                        broadBean.setBroadcastNickname(userBean.getNickname());
                        broadBean.setBroadcastUserId(userBean.getUserId());
                        hotMsg.setBroadcast(broadBean);

                        hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_AGREE_BROASTCAST);

                        String hotMsgContent = mGson.toJson(hotMsg);
                        Log.i(MeetingConfig.TAG,"同意为主播:"+hotMsgContent);
                        mAgoraSigAPI.messageInstantSend(fromUserId,0,hotMsgContent,"");
                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        HotMessage hotMsg = new HotMessage();
                        hotMsg.setUser(MeetUtils.getUserBean(mContext));
                        hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());
                        hotMsg.setBroadcast(MeetingManager.getInstance().getBroadcastBean());
                        hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_REFUSE_SET_BROASTCAST);

                        String hotMsgContent = mGson.toJson(hotMsg);
                        Log.i(MeetingConfig.TAG,"拒绝为主播:"+hotMsgContent);
                        mAgoraSigAPI.messageInstantSend(fromUserId,0,hotMsgContent,"");
                    }
                });

                builder.create().show();
            }
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_REQUEST_BROASTCAST)
        {
             //如果是创建者则处理
            final String fromUserId =String.valueOf(msgHot.getUser().getUserId()) ;
             HotMessage.BroadcastBean bean = MeetingManager.getInstance().getBroadcastBean();
            //            if(mUserId == AgoraManager.getInstance().getBroastcastId())
            if(bean.getBroadcastUserId()==mUserId)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("主播设置");
                String nickName =  msgHot.getUser().getNickname();
                builder.setMessage(nickName +"请求为主播,是否同意？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        HotMessage hotMsg = new HotMessage();
                        hotMsg.setUser(MeetUtils.getUserBean(mContext));
                        hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());

                        //需要将即将成为主播的任务信息 填充进主播
                        hotMsg.setBroadcast(msgHot.getBroadcast());

                        hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_AGREE_SET_BROASTCAST);

                        String hotMsgContent = mGson.toJson(hotMsg);
                        Log.i(MeetingConfig.TAG,"同意请求设置为主播:"+hotMsgContent);
//                        mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
                        mAgoraSigAPI.messageInstantSend(fromUserId,0,hotMsgContent,"");
                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        HotMessage hotMsg = new HotMessage();
                        hotMsg.setUser(MeetUtils.getUserBean(mContext));
                        hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());
                        hotMsg.setBroadcast(MeetingManager.getInstance().getBroadcastBean());
                        hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_REFUSE_BROASTCAST);

                        String hotMsgContent = mGson.toJson(hotMsg);
                        Log.i("MeetingMsg","拒绝请求设置为主播:"+hotMsgContent);
//                        mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
                        mAgoraSigAPI.messageInstantSend(fromUserId,0,hotMsgContent,"");
                    }
                });

                builder.create().show();
            }
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_AGREE_BROASTCAST)
        {
            int broadcastUserId = MeetingManager.getInstance().getMeetingBean().getMeetingUserId();
            if(broadcastUserId==mUserId) {
                Log.i(MeetingConfig.TAG, "会议创建者同意主播将自己设置主播 发送通知主播变更");
                HotMessage hotMsg = new HotMessage();
                HotMessage.UserBean userBean = MeetUtils.getUserBean(mContext);
                hotMsg.setUser(userBean);
                hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());

                //将过来的信息中主播设置为主播
                hotMsg.setBroadcast(msgHot.getBroadcast());
                hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_CHANGE_BROASTCAST);

                String hotMsgContent = mGson.toJson(hotMsg);
                Log.i("MeetingMsg", "同意主播:" + hotMsgContent);
                mAgoraSigAPI.messageChannelSend(mRoomId, hotMsgContent, "");
            }
            else
            {
                Log.i(MeetingConfig.TAG, "无权限设置");
            }
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_AGREE_SET_BROASTCAST)
        {

                Log.i(MeetingConfig.TAG,"同意设置主播 发送通知主播变更");
                HotMessage hotMsg = new HotMessage();
                HotMessage.UserBean userBean = MeetUtils.getUserBean(mContext);
                hotMsg.setUser(userBean);
                hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());

                //将自己为主播
                HotMessage.BroadcastBean bean = new HotMessage.BroadcastBean();
                bean.setBroadcastUserId(userBean.getUserId());
                bean.setBroadcastNickname(userBean.getNickname());
                bean.setBroadcastId(userBean.getHottvId());
                bean.setBroadcastAvatar("无");
                hotMsg.setBroadcast(bean);
                hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_CHANGE_BROASTCAST);

                String hotMsgContent = mGson.toJson(hotMsg);
                Log.i("MeetingMsg","同意请求将自己设置为主播:"+hotMsgContent);
                //发送广播 替换主播
                mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_REFUSE_BROASTCAST)
        {
            //拒绝则不处理
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_REFUSE_SET_BROASTCAST)
        {
            //拒绝则不处理
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_CHANGE_BROASTCAST)
        {
            //设置现在的主播
            Log.i("MeetingMsg","MESSAGE_TYPE_CHANGE_BROASTCAST");
            AgoraManager.getInstance().setBroastcast();
            AgoraManager.getInstance().setUserType(msgHot.getBroadcast().getBroadcastUserId(),MeetingConfig.BROADCASTER_TYPE);
            if(msgHot.getMeeting()!=null)
            {
                MeetingManager.getInstance().setMeetingBean(msgHot.getMeeting());
            }
            if(msgHot.getBroadcast()!=null)
            {
                MeetingManager.getInstance().setBroadcastBean(msgHot.getBroadcast());
            }

            //处理界面
            updateUI();
//            updateAIUI();
            //处理是否进
            if(mIsSpeak)
            {
                enableAudio(true);
            }
            else
            {
                if(mUserId==AgoraManager.getInstance().getBroastcastId())
                {
                    enableAudio(true);
                }
                else
                {
                    enableAudio(false);
                }
            }
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_NOTICE_INFO)
        {
            //处理新加入会议的人员信息
            HotMessage.UserBean userBean = msgHot.getUser();
            if(!TextUtils.isEmpty(userBean.getHottvId()) && userBean.getUserId()!=0)
            {
                //添加用户
                if(MeetingManager.getInstance().getUserNum()>=MeetingConfig.MAX_NUM)
                {
                    showToast("超过视频最大人数");
                    return;
                }

                MeetingManager.getInstance().addUserBean(userBean);
                if(userBean.getUserId()==mUserId)
                {
                    Log.i("MeetingMsg","本机返回 不用处理");
                    return;
                }

               AgoraManager.getInstance().setUserType(userBean.getUserId(),MeetingConfig.AUDIENCE_TYPE);

                //维护列表
               HotMessage.BroadcastBean broadcastBean = msgHot.getBroadcast();
               if(broadcastBean!=null){
                   if(broadcastBean.getBroadcastUserId()==userBean.getUserId())
                   {
                       AgoraManager.getInstance().addUser(userBean.getUserId(),MeetingConfig.BROADCASTER_TYPE);
                   }
                   else
                   {
                       AgoraManager.getInstance().addUser(userBean.getUserId(),MeetingConfig.AUDIENCE_TYPE);
                   }
                   //设置主播
                   if(!TextUtils.isEmpty(broadcastBean.getBroadcastId()) && broadcastBean.getBroadcastUserId()!=0)
                   {
                       MeetingManager.getInstance().setBroadcastBean(broadcastBean);
                       if(AgoraManager.getInstance().getBroastcastId() != broadcastBean.getBroadcastUserId())
                       {
                           AgoraManager.getInstance().setUserType(broadcastBean.getBroadcastUserId(),MeetingConfig.BROADCASTER_TYPE);
                       }
                   }
               }

               //设置会议信息
                HotMessage.MeetingBean meetingBean = msgHot.getMeeting();
                if(meetingBean!=null &&!TextUtils.isEmpty(meetingBean.getMeetingId()) && meetingBean.getMeetingUserId()!=0)
                {

                    if(meetingBean.getMeetingUserId()!= MeetingManager.getInstance().getMeetingBean().getMeetingUserId()
                            && MeetingManager.getInstance().getMeetingBean().getMeetingUserId()==0)
                    {
                        Log.i(MeetingConfig.TAG,"设置meeting 信息");
                        MeetingManager.getInstance().setMeetingBean(meetingBean);
                    }
                }
               //处理界面
                Log.i("MeetingMsg","updateUI 新增人员处理");
//                updateUI();
                updateAIUI(userBean.getUserId());
            }
        }
        //收到通知结束会议
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_QUIT)
        {
            Log.i("MeetingMsg","结束会议");
            if(account.equals(String.valueOf(mUserId)))
            {
                return;
            }
//            showToast("会议结束，正在关闭！！！");
//            new Handler().postDelayed(new Runnable() {
//
//                @Override
//                public void run() {
//                    //do something
//                    finish();
//                }
//            }, 5000);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("会议结束");
            builder.setMessage("会议已经结束，是否结束？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });

            builder.create().show();
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_SHUT_UP)
        {
            mIsSpeak = false;
            if(mUserId!=AgoraManager.getInstance().getBroastcastId())
            {
                Log.i("MeetingMsg","如果不是主播，则禁言");
                enableAudio(false);

//                muteLocalAudioStream(true);
            }
            else
            {
                Log.i("MeetingMsg","如果是主播，则不禁言");
                enableAudio(true);
//                muteLocalAudioStream(false);
            }
        }
        else  if(msgHot.getSignalType() == HotMessage.MESSAGE_TYPE_SPEAK)
        {
            mIsSpeak = true;
            enableAudio(true);
//            muteLocalAudioStream(false);
        }
    }

    //通过uid创建surfaceView
    private void createSurfaceById(final int uid)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(uid);
                if(surfaceView==null) {
                    Log.i(MeetingConfig.TAG, "surfaceView is null create a new surfaceview ");
                    surfaceView = RtcEngine.CreateRendererView(getApplicationContext());
                    MeetingManager.getInstance().insertSurfaceView(uid, surfaceView);
                }

                mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid));

                mRtcEngine.setRemoteVideoStreamType(uid, Constants.VIDEO_STREAM_LOW);

//                updateUI();
                updateAIUI(uid);
            }
        });
    }

    private void removeSurfaceById(final int uid)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(uid);
                if(surfaceView!=null)
                {
                    Log.i(MeetingConfig.TAG,"-----------doRemoveRemoteUi-");
                    AgoraUtils.checkSurfaceView(surfaceView);
                }

                MeetingManager.getInstance().removeSurfaceView(uid);
            }
        });
    }

    //发送消息 到广播告诉自己的信息
    private void sendMsgUserInfo()
    {
        HotMessage hotMsg = new HotMessage();
        hotMsg.setUser(MeetUtils.getUserBean(mContext));
        if(mUserId==AgoraManager.getInstance().getBroastcastId())
        {
            hotMsg.setMeeting(MeetingManager.getInstance().getMeetingBean());
            hotMsg.setBroadcast(MeetingManager.getInstance().getBroadcastBean());
        }
        hotMsg.setSignalType(HotMessage.MESSAGE_TYPE_NOTICE_INFO);

        String hotMsgContent = mGson.toJson(hotMsg);
        Log.i("MeetingMsg","-----------sendMsgUserInfo："+hotMsgContent);
        mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
    }

    //更新界面
    private void updateUI()
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //处理视频流
                handleUI(mVideoFirst);
                handleBroadcastUI(mVideoFirst);

                //处理视频列表
                handleVideoList(mVideoFirst);

                //处理白板
                handleWhite(mVideoFirst);
            }
        });
    }


    //智能更新页面更新界面
    private void updateAIUI(final int uid)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //如果是视频优先
                if(mVideoFirst)
                {
                    //如果是主播
                    if(uid==AgoraManager.getInstance().getBroastcastId())
                    {
                        Log.i("MeetingMsg","mVideoFirst handleBroadcastUI");
                        handleBroadcastUI(mVideoFirst);
                    }
                    else  //如果不是主播
                    {
                        Log.i("MeetingMsg","mVideoFirst handleVideoList");
                        handleVideoList(mVideoFirst);
                    }
                }
                else
                {
                    Log.i("MeetingMsg","mVideoFirst handleVideoList");
                    handleVideoList(mVideoFirst);
                }

                handleWhite(mVideoFirst);
            }
        });
    }

    private void showToast(final String content)
    {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(mContext,content,Toast.LENGTH_LONG).show();
//            }
//        });

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext,content,Toast.LENGTH_LONG).show();
            }
        });
    }

    private void handleDown()
    {
        boolean stillProcess = WhiteManager.getInstance().checkProcess();
        if(stillProcess)
        {
            showToast("剩下的还在处理中");
        }
        else
        {
            int nextCur = WhiteManager.getInstance().getNextPageCur();
            if(nextCur!=-1)
            {
                if(mRoom!=null) {
                    mRoom.setScenePath(MeetingConfig.SCENE_DIR + "/" + String.valueOf(nextCur));
                    mTxtPage.setText("当前页："+(WhiteManager.getInstance().getCurrentPage()+1)+"/"+WhiteManager.getInstance().getTotalPage());

                }
            }else
            {
                Toast.makeText(mContext,"已经是最后一页了",Toast.LENGTH_LONG).show();
            }
        }
    }

    private void handleUp()
    {
        int nextCur = WhiteManager.getInstance().getBeforePageCur();
        if(nextCur!=-1)
        {
            if(mRoom!=null) {
                mTxtPage.setText("当前页："+(WhiteManager.getInstance().getCurrentPage()+1)+"/"+WhiteManager.getInstance().getTotalPage());
                mRoom.setScenePath(MeetingConfig.SCENE_DIR + "/" + String.valueOf(nextCur));
            }
        }else
        {
            showToast("已经是第一页了");
        }
    }

    private void sendCanVoice(int type)
    {
        HotMessage msg = new HotMessage();
        msg.setSignalType(type);

        String hotMsgContent = mGson.toJson(msg);
        Log.i("MeetingMsg","-------sendMsgUserInfo："+hotMsgContent);
        mAgoraSigAPI.messageChannelSend(mRoomId,hotMsgContent,"");
    }

    private void enableVideo(final  boolean enable)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if(mRtcEngine!=null)
                {
                    Log.i(MeetingConfig.TAG,"enableVideo enable:"+enable);
                    mRtcEngine.enableVideo();
                    mRtcEngine.enableLocalVideo(enable);
                }
            }
        });
    }

    private void enableAudio(final boolean enable)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mRtcEngine!=null)
                {
                    Log.i(MeetingConfig.TAG,"enableAudio enable:"+enable);
//                    if(enable)
//                    {
//                        mRtcEngine.enableAudio();
//                    }else
//                    {
//                        mRtcEngine.disableAudio();
//                    }
                    //该方法不影响接收或播放远端音频流，enableLocalAudio(false) 适用于只听不发的用户场景
                    mRtcEngine.enableLocalAudio(enable);
                }
            }
        });
    }

    //停止/恢复发送本地音频流 该方法不影响录音状态，并没有禁用麦克风。
    private void muteLocalAudioStream(final boolean enable)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mRtcEngine!=null)
                {
                    Log.i(MeetingConfig.TAG,"enableAudio enable:"+enable);
                    mRtcEngine.muteLocalAudioStream(enable);
                }
            }
        });
    }
}
